import { WinBase } from "../wins/WinBase";
import { ccs } from "./services";
import { UICtrl } from "./UiCtrl";
export interface KeyObject<T> {
        [index: string] : T;
}
export class winClass extends cc.Component{

    private _winScripts: KeyObject<WinBase> = {};
    private _winCtrl:UICtrl = null;

    // 设置操作
    setWinCtrl(ctrl: UICtrl) {
        this._winCtrl = ctrl;
    }

    getWinCtrl(): UICtrl {
        return this._winCtrl;
    }
    
    // async showWin(winName: string, args?: object, cb?: Function){
    //     let myWin = cc.find(winName);
    //     if(myWin){
    //         myWin.zIndex = 100;
    //     }else {
    //         let win = await ccs.resMgr.loadPrefab("prefab/wins/" + winName);
    //         cc.find('Canvas').addChild(win);
    //     }
        
    // }
    // closeWin(winName: string) {
    //     this.node.destroy();
    // }

    showWin(winName: string, args?: object, func?: Function, target?: object) {
        console.log('showWin:' + winName);
        let script = this._winScripts[winName]; //获取预制对象

        if(script && cc.isValid(script.node)) {
            script.node.active = true;
            //script.node.stopAllActions
            script.setInitArgs(args);
            // script.onUpdateArgs(args);
            ccs.gf.doCallback(func, target, script);
            return ;
        }
        this.newWin(winName, args, func, target);
    }
     newWin(winName:string, args?:object, func?:Function, target?:object) {
        if(!this._winCtrl) {
            return ;
        }

        this._winCtrl.showWin(winName, args, (script: WinBase)=>{
            this._winScripts[winName] = script; 
        }, this);
    }
    // 显示隐藏
    setWinActive(winName:string, active:boolean = false) {
        let script = this.getWinScript(winName);
        if(script) {
            script.node.parent.active = active;
        }
    }
    
    // 清除窗口
    cleanWin(winName:string) {
        if(this._winScripts[winName]) {
            delete this._winScripts[winName];
        }
    }
    // 获取窗口脚本
    getWinScript(winName:string):WinBase {
        return this._winScripts[winName];
    }
    closeWin(winName:string) {
        let script = this.getWinScript(winName);
        if(script) {
            script._close();
            return true;
        }
        
        return false;
    }
    // 关闭所有的窗口
    closeAllWin() {
        for(let winName in this._winScripts) {
            this.closeWin(winName);
        }
        this._winScripts = {};
    }

    // 判断当前是否有弹出的界面(常驻界面不计算在内)
    isPopWin(targetWin:string):boolean {
        for(let winName in this._winScripts) {
            let script = this._winScripts[winName];
            if(script.node.parent.active && winName != targetWin) {
                return true;
            }
        }
        return false;
    }
}